package com.food.eat.config;

import com.food.eat.mapper.OrderMapper;
import com.food.eat.pojo.OrderBase;
import com.food.eat.pojo.bo.OrderDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Slf4j
@Component
public class OrderMintor {

    private static final DelayQueue<OrderDto> delayQueue = new DelayQueue<>();
    private final ExecutorService executorService = Executors.newFixedThreadPool(2);

    @Resource
    private OrderMapper orderMapper;


    /**
     * 延时队列里，添加任方法
     *
     * @param orderDto
     */
    public void addQueue(OrderDto orderDto) {
        delayQueue.add(orderDto);
    }



    @PostConstruct
    public void initEnv () {
        //守护线程
        new Thread(() -> {
            while (true) {
                if(delayQueue.size()>0) {
                    executorService.execute(() -> {
                        log.info("dead thread 【start】 =========守护线程开始执行，处理超时订单=========》");
                        //1;获取订单内容
                        OrderDto take = null;
                        try {
                            take = delayQueue.take();
                            OrderBase orderBase = new OrderBase();
                            orderBase.setOrderId(take.getOrderId());
                            orderBase.setOrderStatus(2);

                            //3；修改订单状态
                            orderMapper.updateOrderByParmaryId(orderBase);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                        log.info("dead thread 【end】=========守护线程执行结束，处理超时订单完成=========》");
                    });

                }
            }

        }).start();

    }
}
